package com.contest.ws;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

public class WsGameNumberHandlerInterceptor implements HandshakeInterceptor {
    //初次握手链接
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, org.springframework.web.socket.WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {

        System.out.println("yyy");
        if (serverHttpRequest instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            if (session != null) {
                //使用userId区分WebSocketHandler，以便定向发送消息
                String userId = (String) session.getAttribute("userId");
                if(StringUtils.isEmpty(userId))
                {
                    userId = servletRequest.getServletRequest().getParameter("userId");
                }
                if (StringUtils.isEmpty(userId)) {
                    map.put("userId", "979264751693598720");
//                   return false;
                    return  true;
                }
                map.put("userId", userId);
            }
        }
        return true;
    }

    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, org.springframework.web.socket.WebSocketHandler webSocketHandler, Exception e) {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) serverHttpRequest;
    }
}
